﻿using CubicFWNet.Application.SystemManager;
using CubicFWNet.Common;
using CubicFWNet.Data.Models;
using CubicFWNet.Mvc.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CubicFWNet.Mvc.Controllers
{
    public class UserController : ControllerBase
    {
        private UserApp _app;
        private RoleApp _roleApp;
        private ModuleApp _moduleApp;

        public UserController()
        {
            _app = new UserApp();
            _roleApp = new RoleApp();
            _moduleApp = new ModuleApp();
        }
        [Authenticate]
        [HttpGet]
        public ViewResult Index()
        {
            return View(_app.GetList());
        }

        //添加或修改组织
        [HttpPost]
        [HandlerAjaxOnly]
        public string Add(User user, string moduleIds)
        {
            try
            {
                user.CreatorId = operatorModel.UserId;
                _app.AddOrUpdate(user,moduleIds.Split(',').ToArray());
            }
            catch (Exception ex)
            {
                Result.Status = "error";
                Result.Message = ex.Message;
            }
            return Result.ToJson();
        }


        //添加或修改组织
        [HttpPost]
        [HandlerAjaxOnly]
        public string UpdateUserPwd(string newPassword = "", string id = "")
        {
            try
            {
                if (string.IsNullOrEmpty(newPassword))
                {
                    Result.Status = "error";
                    Result.Message = "密码不可为空";
                    return Result.ToJson();
                }
                if (string.IsNullOrEmpty(id) || !Common.Common.IsGuidSign(id))
                {
                    Result.Status = "error";
                    Result.Message = "当前用户异常，请刷新页面重试";
                    return Result.ToJson();
                }
                Guid usrId = new Guid(id);
                var user = _app.GetForm(usrId);
                if (user == null)
                {
                    Result.Status = "error";
                    Result.Message = "当前用户不存在";
                    return Result.ToJson();
                }
                //string passwordnew = Md5.md5(newPassword, 32).ToLower();
                user.Password = PasswordHash.CreateHash(newPassword);
                _app.UpdatePwdBy(user);
            }
            catch (Exception ex)
            {
                Result.Status = "error";
                Result.Message = ex.Message;
            }
            return Result.ToJson();
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetFormJson(Guid id)
        {
            var data = _app.GetForm(id);
            return Content(data.ToJson());
        }

        [HttpPost]
        [HandlerAjaxOnly]
        public string Delete(Guid id)
        {
            try
            {
                var del = _app.GetForm(id);
                if (del == null)
                {
                    Result.Status = "error";
                    Result.Message = "未找到该数据";
                    Result.ToJson();
                }
                _app.Delete(id);
            }
            catch (Exception e)
            {
                Result.Status = "error";
                Result.Message = e.Message;
            }
            return Result.ToJson();
        }

        public ActionResult GetRoles(Guid userId)
        {
            var roles = _roleApp.Load();
            var userRoles = new List<Guid>();
            if (userId != Guid.Empty)
            {
                userRoles = _app.LoadRole(userId);
            }
            var treeList = new List<TreeViewModel>();
            foreach (var item in roles)
            {
                TreeViewModel tree = new TreeViewModel();
                tree.id = item.Id.ToString();
                tree.text = item.Name;
                tree.value = item.Id.ToString();
                tree.parentId = "";
                tree.isexpand = true;
                tree.complete = true;
                tree.showcheck = true;
                tree.checkstate = userRoles.Count(t => t == item.Id);
                tree.hasChildren = false;
                tree.img = "";
                treeList.Add(tree);
            }
            return Content(treeList.TreeViewJson());
        }

        //用户分配模块
        public ActionResult GetModuleTree(Guid userId)
        {
            var moduledata = _moduleApp.GetList();
            var authorizeModule = new List<Module>();
            if (userId != Guid.Empty)
            {
                authorizeModule = _moduleApp.GetModulesQuery(userId);
            }
            var treeList = new List<TreeViewModel>();
            foreach (Module item in moduledata)
            {
                TreeViewModel tree = new TreeViewModel();
                bool hasChildren = moduledata.Count(t => t.ParentId == item.Id) == 0 ? false : true;
                tree.id = item.Id.ToString();
                tree.text = item.Name;
                tree.value = item.Id.ToString();
                tree.parentId = item.ParentId.ToString();
                tree.isexpand = true;
                tree.complete = true;
                tree.showcheck = true;
                tree.checkstate = authorizeModule.Count(t => t.Id == item.Id);
                tree.hasChildren = true;
                tree.img = "";
                treeList.Add(tree);
            }
            return Content(treeList.TreeViewJson());
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        public ActionResult UpdatePwd()
        {
            ViewBag.User = operatorModel;
            return View();
        }

        [HttpPost]
        public ActionResult UpdatePwd(FormCollection fc)
        {
            string oldPwd = fc["Old"];
            string newPwd = fc["New1"];
            int res = _app.UpdatePwd(operatorModel.UserId, oldPwd, newPwd);
            if (res == -1)
            {
                ViewBag.Info = "该用户不存在！";
            }
            else if (res == -2)
            {
                ViewBag.Info = "旧密码输入错误！";
            }
            else if (res == 0)
            {
                ViewBag.Info = "修改成功！";
                return RedirectToAction("OutLogin", "Login");
            }
            ViewBag.User = operatorModel;
            return View();
        }
    }
}